﻿using LiveChartsCore.Defaults;
using NewLife.Data;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UIWindows.Models.Homes;
using UIWindows.Tools.Helper;
using UIWindows.UserControls;
using XingLucifer.IBase.Enums;
using static Google.Protobuf.Reflection.SourceCodeInfo.Types;
using static log4net.Appender.RollingFileAppender;

namespace UIWindows.GlobalStatics
{
    [Attributes.Singleton]
    public class HomeStatic
    {
        public ObservableCollection<TrendModel> Trend { get; set; }
        public EquipmentTimeModel EquipmentTime { get; set; }
        public AsyncObservableCollection<MessageBeforeScanCodeModel> Battery_BeforeScanCode { get; set; }
     
        public AsyncObservableCollection<MessageBeforeWeighingModel> Battery_BeforeWeighing { get; set; }
        public AsyncObservableCollection<MessageAltimetryModel> Battery_Altimetry { get; set; }

        public AsyncObservableCollection<MessageCCDModel> Battery_CCD { get; set; }



        public AsyncObservableCollection<Kinlo.Entitys.ProductionData> Battery_AfterFluidInjection { get; set; }

        public AsyncObservableCollection<Kinlo.Entitys.ProductionData> Battery_ShortCircuit { get; set; }

        //public AsyncObservableCollection<MessageShortCircuitRJ6901AModel> Battery_ShortCircuit { get; set; }

        public AsyncObservableCollection<Kinlo.Entitys.ProductionData> Battery_ShortCicuteProductionData { get; set; }

        public ChartDataModel ChartData { get; set; }
        public HomeStatic()
        {
            try
            {
                if (System.IO.File.Exists(GlobalStatic.EquipmentTimePath))
                {
                    EquipmentTime = System.Text.Json.JsonSerializer.Deserialize<EquipmentTimeModel>(System.IO.File.ReadAllText(GlobalStatic.EquipmentTimePath, Encoding.UTF8), GlobalStatic.Options);
                }
                else
                {
                    EquipmentTime = new EquipmentTimeModel();
                }
            }
            catch (Exception)
            {
                EquipmentTime = new EquipmentTimeModel();
            }
            try
            {
                if (System.IO.File.Exists(GlobalStatic.ChartDataPath))
                {
                    ChartData = System.Text.Json.JsonSerializer.Deserialize<ChartDataModel>(System.IO.File.ReadAllText(GlobalStatic.ChartDataPath, Encoding.UTF8), GlobalStatic.Options);
                }
                else
                {
                    ChartData = new ChartDataModel();
                }
            }
            catch (Exception)
            {
                ChartData = new ChartDataModel();
            }
            ChartData.OV_AfterWeighingPassingRate = new ObservableValue();
            ChartData.OV_LessLiquid = new ObservableValue();
            ChartData.OV_MultiLiquid = new ObservableValue();
            ChartData.OV_LiquidInjection_PassingRate = new ObservableValue();
            ChartData.OV_AfterWeighingPassingRate.Value = ChartData.AfterWeighingPassingRate;
            ChartData.OV_LessLiquid.Value = ChartData.NG_LessLiquid;
            ChartData.OV_MultiLiquid.Value = ChartData.NG_MultiLiquid;
            ChartData.OV_LiquidInjection_PassingRate.Value = ChartData.LiquidInjection_PassingRate;
            Trend = new ObservableCollection<TrendModel>();
            Battery_BeforeScanCode = new AsyncObservableCollection<MessageBeforeScanCodeModel>();
            //Battery_ShortCircuit = new AsyncObservableCollection<MessageShortCircuitRJ6901AModel>();
            Battery_BeforeWeighing = new AsyncObservableCollection<MessageBeforeWeighingModel>();



            Battery_CCD = new AsyncObservableCollection<MessageCCDModel>();

            Battery_AfterFluidInjection = new AsyncObservableCollection<Kinlo.Entitys.ProductionData>();


            Battery_ShortCircuit = new AsyncObservableCollection<Kinlo.Entitys.ProductionData>();

            Battery_ShortCicuteProductionData = new AsyncObservableCollection<Kinlo.Entitys.ProductionData>();

            Battery_Altimetry = new AsyncObservableCollection<MessageAltimetryModel>();
        }

        public void SaveEquipmentTime() => System.IO.File.WriteAllText(GlobalStatic.EquipmentTimePath, System.Text.Json.JsonSerializer.Serialize(EquipmentTime, GlobalStatic.Options), Encoding.UTF8);
        public void SaveChartData() => System.IO.File.WriteAllText(GlobalStatic.ChartDataPath, System.Text.Json.JsonSerializer.Serialize(ChartData, GlobalStatic.Options), Encoding.UTF8);
        /// <summary>
        /// 前扫码信息输出
        /// </summary>
        /// <param name="barcode">条码</param>
        /// <param name="message">结果</param>
        /// <param name="dateTime">时间</param>
        public void AddInBattery(string barcode, ResultTypes message, DateTime dateTime, int location)
        {
            for (int i = 0; i < 3; i++)
            {
                try
                {
                    Battery_BeforeScanCode.Insert(0, new MessageBeforeScanCodeModel()
                    {
                        BarCode = barcode,
                        Location = location,
                        Result = message,
                        Time = dateTime.ToString("yyyy/MM/dd HH:mm:ss")
                    });
                    if (Battery_BeforeScanCode.Count > 400)
                    {
                        Battery_BeforeScanCode.RemoveAt(399);
                    }
                    return;
                }
                catch (Exception ex)
                {
                    $"前扫码 第 [{i}] 次 插入日志异常：{ex.ToString().Trim()}".RunLog(MessageLevelType.错误);
                }
            }
        }
        /// <summary>
        /// 测高数据信息输出
        /// </summary>
        /// <param name="barcode">条码</param>
        /// <param name="message">结果</param>
        /// <param name="dateTime">时间</param>
        public void AddInAltimetry(Kinlo.Entitys.ProductionData production)
        {
            for (int i = 0; i < 3; i++)
            {
                try
                {
                    Battery_Altimetry.Insert(0, new MessageAltimetryModel()
                    {
                        BarCode = production.BarCode,
                        Result = production.AltimetryResult,
                        AltimetryValue = production.AltimetryValue,
                        Time = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"),
                        ScanCodeResult = production.ResultScanCodeBefore,
                        ScanCodeTime = production.TimeScanCodeBefore.GetDateTime().ToString("yyyy/MM/dd HH:mm:ss"),
                    });
                    if (Battery_BeforeScanCode.Count > 400)
                    {
                        Battery_BeforeScanCode.RemoveAt(399);
                    }
                    return;
                }
                catch (Exception ex)
                {
                    $"测高数据 第 [{i}] 次 插入日志异常：{ex.ToString().Trim()}".RunLog(MessageLevelType.错误);
                }
            }
        }
        /// <summary>
        /// CCD数据信息输出
        /// </summary>
        /// <param name="production"></param>
        public void AddInCCD(Kinlo.Entitys.ProductionData production)
        {
            for (int i = 0; i < 3; i++)
            {
                try
                {
                    Battery_CCD.Insert(0, new MessageCCDModel()
                    {
                        BarCode = production.BarCode,
                        ResultCCD1 = production.ResultCCD1,
                        ResultCCD2 = production.ResultCCD2,
                        Time = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"),
                    });
                    if (Battery_CCD.Count > 400)
                    {
                        Battery_CCD.RemoveAt(399);
                    }
                    return;
                }
                catch (Exception ex)
                {
                    $"CCD数据 第 [{i}] 次 插入日志异常：{ex.ToString().Trim()}".RunLog(MessageLevelType.错误);
                }
            }
        }
        /// <summary>
        /// 短路测试仪
        /// </summary>
        /// <param name="barcode">条码</param>
        /// <param name="message">信息</param>
        /// <param name="dateTime">时间</param>
        /// <param name="production">实体</param>
        public void AddShortCircuitBattery(Kinlo.Entitys.ProductionData production)
        {
            //var model = Battery_ShortCircuit.FirstOrDefault(x => x.SnowflakeId == production.SnowflakeId);
            //if (model != null)
            //{
            //    //model.ResistanceTestTime = production.TimeHousing.ToString("yyyy/MM/dd HH:mm:ss");
            //    //model.ResistanceTestValue = production.ResistanceTestValue;
            //    return;
            //}
            var model = Battery_ShortCircuit.FirstOrDefault(x => x.SnowflakeId == production.SnowflakeId);
            if (_batteryInjectionUpdate == null)
            {
                _batteryInjectionUpdate = ConversionHelper.CopyXCodeEntity<Kinlo.Entitys.ProductionData, Kinlo.Entitys.ProductionData>();
            }
            if (model != null)
            {
                _batteryInjectionUpdate.Invoke(production, model);
                return;
            }
            for (int i = 0; i < 3; i++)
            {
                try
                {
                    Battery_ShortCircuit.Insert(0, production);
                    if (Battery_ShortCircuit.Count > 400)
                    {
                        Battery_ShortCircuit.RemoveAt(399);
                    }
                    return;
                }
                catch (Exception ex)
                {
                    $"短路测试 第 [{i}] 次 插入日志异常：{ex.ToString().Trim()}".RunLog(MessageLevelType.错误);
                }
            }
        }

        /// <summary>
        /// 前称重信息输出
        /// </summary>
        /// <param name="barcode">条码</param>
        /// <param name="message">结果</param>
        /// <param name="dateTime">时间</param>
        /// <param name="production">实体</param>
        public void AddBeforeWeighingBattery(string barcode, ResultTypes message, DateTime dateTime, double weighing, int location, Kinlo.Entitys.ProductionData production)
        {
            for (int i = 0; i < 3; i++)
            {
                try
                {
                    Battery_BeforeWeighing.Insert(0, new MessageBeforeWeighingModel() { 
                        BarCode = barcode, 
                        Result = message, 
                        Time = dateTime.ToString("yyyy/MM/dd HH:mm:ss"),
                        FormerWeighing = weighing,
                        LocationFormerWeighing = location,
                    });
                    if (Battery_BeforeWeighing.Count > 400)
                    {
                        Battery_BeforeWeighing.RemoveAt(399);
                    }
                    return;
                }
                catch (Exception ex)
                {
                    $"前称重 第 [{i}] 次 插入日志异常：{ex}".RunLog(MessageLevelType.错误);
                }
            }
        }
        /// <summary>
        /// 注液后工序图表
        /// </summary>
        /// <param name="production"></param>
        public void AddOutBattery(Kinlo.Entitys.ProductionData production)
        {
            var model = Battery_AfterFluidInjection.FirstOrDefault(x => x.SnowflakeId == production.SnowflakeId);
            if (_batteryInjectionUpdate == null)
            {
                _batteryInjectionUpdate = ConversionHelper.CopyXCodeEntity<Kinlo.Entitys.ProductionData, Kinlo.Entitys.ProductionData>();
            }
            if (model != null)
            {
                _batteryInjectionUpdate.Invoke(production, model);
                return;
            }
            for (int i = 0; i < 3; i++)
            {
                try
                {
                    Battery_AfterFluidInjection.Insert(0, production);
                    if (Battery_AfterFluidInjection.Count > 400)
                    {
                        Battery_AfterFluidInjection.RemoveAt(399);
                    }
                    return;
                }
                catch (Exception ex)
                {
                    $"注液后 第 [{i}] 次 插入日志异常：{ex.ToString().Trim()}".RunLog(MessageLevelType.错误);
                }
            }
        }


        private Action<Kinlo.Entitys.ProductionData, Kinlo.Entitys.ProductionData> _batteryInjectionUpdate;

    }
}
